import { createRouter, createWebHistory } from 'vue-router'
// 获取pinia的router实例
import pinia from '@/store'
import { useRouteStore } from '@/store/modules/useRouteStore.js'
const useRouteStoreEg = useRouteStore(pinia)
// 引入公共组件layout
import Layout from '@/components/layout/index.vue'
// 引入消息提示方法和获取本地存储方法
import { inforMes, GetLocal } from '@/utils/customFun.js'
// 进度条;
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false }) // 进度条初始化

export const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/loginIndex.vue'),
    meta: { requiresAuth: true, hidden: true, title: '登录' },
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    meta: { requiresAuth: true, hidden: false, title: '首页' },
    children: [
      {
        path: 'dashboard',
        name: 'dashboard',
        component: () => import('@/views/dashboard/dashboardIndex.vue'),
        meta: { title: '首页', requiresAuth: false, hidden: false },
      },
    ],
  },
  {
    path: '/',
    component: Layout,
    redirect: '/user',
    meta: { requiresAuth: true, hidden: false, title: '个人中心' },
    children: [
      {
        path: 'user',
        name: 'user',
        component: () => import('@/views/user/userIndex.vue'),
        meta: { title: '个人中心', requiresAuth: true, hidden: false },
      },
    ],
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/notfound/notfoundIndex.vue'),
    meta: { requiresAuth: true, hidden: true, title: '404' },
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

router.beforeEach(async (to, from, next) => {
  if (to.path === '/login') {
    next()
    return
  }

  // 检查是否已登录
  let token = GetLocal('myVuecomponentsToken')

  if (!token) {
    inforMes('未检测到用户信息，请重新登陆！')
    next('/login')
    return
  }
  NProgress.start()
  if (useRouteStoreEg.addRoutes.length === 0) {
    // 获取动态路由
    let routerArr = await useRouteStoreEg.aysncRouterFn()
    // 根据权限过滤动态路由
    let filterRouterArr = useRouteStoreEg.roleRouterFilter(routerArr)
    // 生成所有路由
    useRouteStoreEg.setDynamicRoutes(routes, filterRouterArr)
    // 添加动态路由到router组件
    useRouteStoreEg.addRoutesAct()
    // 重定向到目标路由
    next(to.fullPath)
    NProgress.done()
  } else {
    next()
    NProgress.done()
  }
})
router.afterEach(() => {
  NProgress.done()
})

export default router
